package com.knife.news.action;

import java.io.*;
import org.json.*;

import java.sql.Timestamp;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Random;

import javax.mail.Message;
import javax.mail.MessagingException;
import javax.mail.Multipart;
import javax.mail.Transport;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

import net.coobird.thumbnailator.Thumbnails;
import net.sf.json.JSONArray;

import org.apache.commons.fileupload.FileItem;
import org.hibernate.hql.ast.tree.FromClause;

import com.knife.member.CheckPassword;
import com.knife.member.Organization;
import com.knife.member.OrganizationDAO;
import com.knife.member.Userinfo;
import com.knife.member.UserinfoDAO;
import com.knife.member.Usertype;
import com.knife.member.UsertypeDAO;
import com.knife.news.logic.PicService;
import com.knife.news.logic.PicTypeService;
import com.knife.news.logic.TypeService;
import com.knife.news.logic.impl.CommentServiceImpl;
import com.knife.news.logic.impl.PicServiceImpl;
import com.knife.news.logic.impl.PicTypeServiceImpl;
import com.knife.news.logic.impl.TypeServiceImpl;
import com.knife.news.object.Type;
import com.knife.news.object.Comment;
import com.knife.news.object.Commodity;
import com.knife.news.object.News;
import com.knife.news.object.Pic;
import com.knife.news.object.PicType;
import com.knife.tools.SessionUtil;
import com.knife.util.CommUtil;
import com.knife.util.FileUtil;
import com.knife.web.ActionContext;
import com.knife.web.Globals;
import com.knife.web.Module;
import com.knife.web.Page;
import com.knife.web.WebForm;
import com.knife.web.security.StringAES;
//import com.sun.net.httpserver.HttpContext;

public class UserAction extends BaseCmdAction {
	private HttpSession mySession = ActionContext.getContext().getSession();
	private List<Commodity> cart = new ArrayList<Commodity>();
	private PicTypeService ptDAO = PicTypeServiceImpl.getInstance();
	private PicService picDAO = PicServiceImpl.getInstance();
	private int regStep = 0;
	
	//jlm
	public CommentServiceImpl commentDAO = CommentServiceImpl.getInstance();
	public TypeService typeDAO = TypeServiceImpl.getInstance();
	public Page doInit(WebForm form, Module module) {
		return new Page("reg", "user_reg.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 会员积分
	public Page doScore(WebForm form, Module module) {
		return null;
	}

	// 会员中心
	public Page doIndex(WebForm form, Module module) {
		if (checkLogin()) {
			return new Page("index", "user_index.htm", "html", "/web/"
					+ thisSite.getTemplate() + "/");
		} else {
			return doLogin(form, module);
		}
	}

	// 会员登录
	public Page doLogin(WebForm form, Module module) {
		tid = CommUtil.null2String(form.get("tid"));
		if (tid.length() > 0) {
			thisType = typeDAO.getTypeById(tid);
			form.addResult("tid", tid);
			form.addResult("thisType", thisType);
		}
		// return module.findPage("/web/" + thisSite.getTemplate(),"login");
		return new Page("login", "user_login.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 登录验证
	public Page doSaveLogin(WebForm form, Module module) {
		String msg = "";
		String tid = "";
		boolean isOk = true;
		boolean isLogin = false;
		boolean isMacBind = false;
		Userinfo auser = null;
		UserinfoDAO userDAO = null;
		String url = "";
		String acount = "";
		String password = "";
		String checkpass = "";
		String mac = "";
		int macnums = 1;
		String retUrl = "/index.do";
		// 检查验证码
		String randomCode = (String) mySession.getAttribute("valiCode");
		String submitrandom = CommUtil.null2String(form.get("vcode"));
		if (submitrandom != null) {
			if (!submitrandom.equalsIgnoreCase(randomCode)) {
				msg = "验证码不匹配:" + randomCode;
				isOk = false;
			}
		} else {
			msg = "非法的提交";
			isOk = false;
		}
		acount = CommUtil.null2String(form.get("acount"));
		password = CommUtil.null2String(form.get("password"));
		mac = CommUtil.null2String(form.get("mac"));
		Boolean issave = Boolean.parseBoolean(CommUtil
				.null2String("saveUserInfo"));
		url = CommUtil.null2String(form.get("url"));
		tid = CommUtil.null2String(form.get("tid"));
		// 判断用户是否已登录
		if (isOk) {
			String loginname = "";
			try {
				List UserSessions = com.knife.tools.SessionUtil.getUserList();
				if (UserSessions.size() > 0) {
					for (int i = 0; i < UserSessions.size(); i++) {
						loginname = (String) UserSessions.get(i);
						System.out.println("鍦ㄧ嚎鐢ㄦ埛:" + loginname);
						if (loginname.equalsIgnoreCase(acount)) {
							Map userMaps = com.knife.tools.SessionUtil
									.getUserSessions();
							HttpSession kickuser = (HttpSession) userMaps
									.get(acount);
							if (kickuser != null) {
								kickuser.removeAttribute("loginname");
								kickuser.invalidate();
							} else {
								// 如果session已经失效,直接移出名单
								com.knife.tools.SessionUtil.RemoveUser(acount);
							}
							isOk = true;
							break;
						}
					}
				}
			} catch (Exception e) {
				// msg="请不要重复登录！";
				// isOk=false;
				e.printStackTrace();
			}
		}

		// 检查是否有网卡绑定
		// 2011-12-16注释
		/*
		 * if(mac.trim().length()<=0){ msg="未找到网卡，请安装客户端插件！"; isOk=false;
		 * isLogin=false; }else{ isOk=true; }
		 */

		if (isOk) {
			userDAO = new UserinfoDAO();
			try {
				List<Userinfo> users = userDAO.findActiveByAcount(acount);
				if (users.size() > 0) {
					auser = users.get(0);
				}
			} catch (Exception e) {
				msg = "登陆失败！无效的用户！";
				isLogin = false;
				e.printStackTrace();
			}
			if (auser != null) {
				// if(auser.getPassword().equals(password)){
				if (CheckPassword.validatePassword(auser.getPassword(),
						password)) {
					checkpass = password;
					password = auser.getPassword();
					isLogin = true;
					/*
					 * if (checkpass.equals("123456") && auser.getLogincount()
					 * == 0) { auser.setActive(0); userDAO.update(auser); } /*
					 * if(checkpass.equals("123456") &&
					 * auser.getLogincount()>0){ auser.setActive(0);
					 * auser.setLogincount(auser.getLogincount()+1);
					 * isLogin=false; userDAO.update(auser); }else{
					 * auser.setLogincount(auser.getLogincount()+1);
					 * userDAO.update(auser); }
					 */
					try {
						// 如果是免费用户,默认不绑定网卡
						if (auser.getIsfee() <= 0) {
							macnums = 0;
						}
						// 判断是否绑定网卡
						if (auser.getIsfee() > 0) {
							Usertype ausertype = (new UsertypeDAO())
									.findById(auser.getIsfee());
							if (ausertype.getMacnum() != null) {
								if (ausertype.getMacnum() > 1) {
									macnums = ausertype.getMacnum();
								}
							}
						}
						// 取消绑定网卡开始2011-12-16加
						isMacBind = true;
						macnums = 0;
						// 取消绑定网卡结束
						if (macnums > 0) {
							// 如果已绑定了网卡
							if (auser.getMac() != null) {
								if (auser.getMac().trim().length() > 0) {
									String[] macs = auser.getMac().split(",");
									// System.out.println("bbbbbbbbbbbbbbbbbbbbbb");
									// 如果已经用完了所有绑定名额
									if (macnums <= macs.length) {
										// System.out.println("ccccccccccccccccccccc");
										for (String amac : macs) {
											// System.out.println("dddddddddddddddddddddddd");
											if (mac.trim().length() > 0
													&& amac.trim().length() > 0
													&& mac.equals(amac)) {
												System.out.println("e:" + mac
														+ "+" + amac);
												isMacBind = true;
												break;
											}
										}
									} else {
										auser.setMac(auser.getMac() + "," + mac);
										userDAO.save(auser);
										isMacBind = true;
									}
								} else {
									auser.setMac(mac);
									userDAO.save(auser);
									isMacBind = true;
								}
							}
							// 如果未绑定网卡
							else {
								auser.setMac(mac);
								userDAO.save(auser);
								isMacBind = true;
							}
						}
					} catch (Exception e) {
						// e.printStackTrace();
						msg = "登陆失败！绑定网卡失败！";
						isLogin = false;
					}
					if (isMacBind) {
						try {
							mySession = ActionContext.getContext().getRequest()
									.getSession(true);
						} catch (Exception e) {
						}
						mySession.setAttribute("loginuser", acount);
						System.out.println("设置在线名称:" + acount);
						// msg="登陆成功！";
						isLogin = true;
						onlineUser = (Userinfo) userDAO.findActiveByAcount(
								acount).get(0);
						/*
						 * Cookie loginUser = new Cookie("loginuser",acount);
						 * Cookie loginPassword = new
						 * Cookie("loginpass",MD5.getMD5(password.getBytes()));
						 * if(issave){ loginUser.setMaxAge(Integer.MAX_VALUE);
						 * loginPassword.setMaxAge(Integer.MAX_VALUE); }else{
						 * loginUser.setMaxAge(30*60);
						 * loginPassword.setMaxAge(30*60); }
						 * loginUser.setPath("/"); loginPassword.setPath("/");
						 * response.addCookie(loginUser);
						 * response.addCookie(loginPassword);
						 */
					} else {
						msg = "登陆失败！请不要试图在未绑定网卡的机器上访问客户端";
						isLogin = false;
					}
				} else {
					// session.removeAttribute("uname");
					msg = "登陆失败！用户名密码错误！";
					isLogin = false;
				}
			} else {
				// session.removeAttribute("uname");
				msg = "登陆失败！不存在的用户！";
				isLogin = false;
			}
		}
		if (isLogin) {
			form.addResult("user", onlineUser);
			return doIndex(form, module);
		} else {
			form.addResult("msg", msg);
			return doLogin(form, module);
		}
	}

	// 浼氬憳閫�嚭
	public Page doLogout(WebForm form, Module module) {
		mySession.removeAttribute("loginuser");
		form.addResult("user", null);
		// return module.findPage("/web/" + thisSite.getTemplate(),"logout");
		return new Page("logout", "user_logout.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 会员注册
	public Page doReg(WebForm form, Module module) {
		String templateName = "user_reg.htm";
		if(regStep==0){
			regStep = CommUtil.null2Int(form.get("step"));
		}
		if (regStep == 0) {
			List<Organization> og = new ArrayList<Organization>();
			OrganizationDAO ogDAO = new OrganizationDAO();
			og = ogDAO.findAll();
			if (og.size() > 0) {
				form.addResult("oglist", og);
			}
		} else if (regStep == 1) {
			String ogvalue = CommUtil.null2String(form.get("ogvalue"));
			if (ogvalue.length() > 0) {
				form.addResult("ogvalue", ogvalue);
			}
		}
		form.addResult("step", regStep + 1);
		if (regStep > 0) {
			templateName = "user_reg_" + regStep + ".htm";
		}
		return new Page("reg", templateName, "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// VIP注册
	public Page doRegVIP(WebForm form, Module module) {
		String templateName = "user_regv.htm";
		regStep = CommUtil.null2Int(form.get("step"));
		if (regStep == 0) {
			List<Organization> og = new ArrayList<Organization>();
			OrganizationDAO ogDAO = new OrganizationDAO();
			og = ogDAO.findAll();
			if (og.size() > 0) {
				form.addResult("oglist", og);
			}
		} else if (regStep == 1) {
			String ogvalue = CommUtil.null2String(form.get("ogvalue"));
			if (ogvalue.length() > 0) {
				form.addResult("ogvalue", ogvalue);
			}
		}
		form.addResult("step", regStep + 1);
		if (regStep > 0) {
			templateName = "user_regv_" + regStep + ".htm";
		}
		return new Page("reg", templateName, "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	
	public Page doRegCheckAcount(WebForm form , Module module) throws JSONException{
		UserinfoDAO userDAO = new UserinfoDAO();
		
		String msg ="";
		//String acount = CommUtil.null2String("acount");
		Userinfo newUser = (Userinfo) form.toPo(Userinfo.class);
		if(newUser.getAcount()==""){ 
			msg= "";
		}
		
		List<Userinfo> checkListaccount1 = new ArrayList();
		try {
			checkListaccount1 = userDAO.findByAcount(newUser.getAcount());
			//checkListaccount = userDAO.findByAcount(acount);
			form.addResult("userList", checkListaccount1);
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(newUser.getAcount()!=""){ 
			if ("admin".equals(newUser.getAcount())) {
				msg = "注册失败！不能使用关键字admin";
			} else {
				if (checkListaccount1.size() > 0) {
					msg = "* 此昵称太受欢迎了，换一个试试。";
				} else {
					msg = "  √";
				}
			}
		}
		form.addResult("msg", msg);
		
		return module.findPage("ajax");
	}
	
	
	// 保存注册
	public Page doSaveReg(WebForm form, Module module) {
		String msg = "";
		String password = "123456";
		Boolean isreg = true;
		regStep = CommUtil.null2Int(form.get("step"));
		// 检查验证码
		String randomCode = (String) mySession.getAttribute("valiCode");
		String submitrandom = CommUtil.null2String(form.get("vcode"));
		if (submitrandom != null) {
			if (!submitrandom.equals(randomCode)) {
				msg = "验证码不匹配:" + submitrandom + "/" + randomCode;
				isreg = false;
			}
		} else {
			msg = "非法的提交";
			isreg = false;
		}
		// 销毁所有会员标识
		mySession.removeAttribute("loginuser");
		Userinfo newUser = (Userinfo) form.toPo(Userinfo.class);
		if ("admin".equals(newUser.getAcount())) {
			msg = "注册失败！不能使用关键字admin";
			isreg = false;
		}
		if (newUser.getSex() == null) {
			newUser.setSex(true);
		}
		UserinfoDAO userDAO = new UserinfoDAO();
		List checkList = new ArrayList();
		try {
			checkList = userDAO.findByEmail(newUser.getEmail());
		} catch (Exception e) {
		}
		if (checkList.size() > 0) {
			msg = "注册失败！邮箱已使用";
			isreg = false;
		}
		List<Userinfo> checkListaccount1 = new ArrayList();
		try {
			checkListaccount1 = userDAO.findByAcount(newUser.getAcount());
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(checkListaccount1.size() > 0){ 
			msg = "此昵称太受欢迎了，换一个试试。";
			isreg = false;
		}
		if (isreg) {
			password = CheckPassword.generatePassword(newUser.getPassword());
			newUser.setPassword(password);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date applyDate = dateFormat.parse(form.get("birthday")
						.toString());
				Timestamp applyTime = new Timestamp(applyDate.getTime());
				newUser.setBirthday(applyTime);
			} catch (Exception e) {
			}
			try {
				Date applyDate1 = dateFormat.parse(form.get("sysj")
						.toString());
				Timestamp applyTime1 = new Timestamp(applyDate1.getTime());
				newUser.setSysj(applyTime1);
			} catch (Exception e) {
			}
			newUser.setIsfee(0);
			try {
				userDAO.save(newUser);
				msg = "跳到激活";
				return doSendActiveMail(form, module);
			} catch (Exception e) {
				msg = "注册失败！";
				System.out.println("注册错误:" + e.getMessage());
				form.addResult("msg", msg);
				form.addResult("tmpUser", newUser);
				return doReg(form, module);
			}
		} else {
			form.addResult("msg", msg);
			form.addResult("tmpUser", newUser);
			return doReg(form, module);
		}
	}

	// 保存VIP注册
	public Page doSaveRegVIP(WebForm form, Module module) {
		String msg = "";
		String password = "123456";
		Boolean isreg = true;
		// 检查验证码
		String randomCode = (String) mySession.getAttribute("valiCode");
		String submitrandom = CommUtil.null2String(form.get("vcode"));
		if (submitrandom != null) {
			if (!submitrandom.equals(randomCode)) {
				msg = "验证码不匹配:" + submitrandom + "/" + randomCode;
				isreg = false;
			}
		} else {
			msg = "非法的提交";
			isreg = false;
		}
		// 销毁所有会员标识
		mySession.removeAttribute("loginuser");
		Userinfo newUser = (Userinfo) form.toPo(Userinfo.class);
		if ("admin".equals(newUser.getAcount())) {
			msg = "注册失败！不能使用关键字admin";
			isreg = false;
		}
		if (newUser.getSex() == null) {
			newUser.setSex(true);
		}
		UserinfoDAO userDAO = new UserinfoDAO();
		List checkList = new ArrayList();
		try {
			checkList = userDAO.findByEmail(newUser.getEmail());
		} catch (Exception e) {
		}
		if (checkList.size() > 0) {
			msg = "注册失败！邮箱已使用";
			isreg = false;
		}
		List<Userinfo> checkListaccount1 = new ArrayList();
		try {
			checkListaccount1 = userDAO.findByAcount(newUser.getAcount());
		} catch (Exception e) {
			// TODO: handle exception
		}
		if(checkListaccount1.size()>0){ 
			msg = "此昵称太受欢迎了，换一个试试。";
			isreg = false;
		}
		if (isreg) {
			password = CheckPassword.generatePassword(newUser.getPassword());
			newUser.setPassword(password);
			SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
			try {
				Date applyDate = dateFormat.parse(form.get("birthday")
						.toString());
				Timestamp applyTime = new Timestamp(applyDate.getTime());
				newUser.setBirthday(applyTime);
			} catch (Exception e) {
			}
			try {
				Date applyDate1 = dateFormat.parse(form.get("sysj")
						.toString());
				Timestamp applyTime1 = new Timestamp(applyDate1.getTime());
				newUser.setSysj(applyTime1);
			} catch (Exception e) {
			}
			// 鑹哄憳浼氬憳
			if(newUser.getIsfee()<=0){
				newUser.setIsfee(1);
			}
			try {
				userDAO.save(newUser);
				msg = "跳到激活";
				return doSendActiveMail(form, module);
			} catch (Exception e) {
				msg = "注册失败！";
				System.out.println("注册错误:" + e.getMessage());
				form.addResult("msg", msg);
				form.addResult("tmpUser", newUser);
				return doRegVIP(form, module);
			}
		} else {
			form.addResult("msg", msg);
			form.addResult("tmpUser", newUser);
			return doRegVIP(form, module);
		}
	}

	// 忘记密码
	public Page doPassword(WebForm form, Module module) {
		tid = CommUtil.null2String(form.get("tid"));
		if (tid.length() > 0) {
			thisType = typeDAO.getTypeById(tid);
			form.addResult("tid", tid);
			form.addResult("thisType", thisType);
		}
		// return module.findPage("/web/" + thisSite.getTemplate(),"password");
		return new Page("password", "user_password.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 修改个人资料
	public Page doProfile(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		return new Page("password", "user_profile.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 修改密码
	public Page doEditPassword(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		return new Page("password", "user_edit_password.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 忘记密码--发送手机验证码（金客会）
	/*
	 * param : mobile 手机号 validateCode 手机验证码
	 */
	public Page doSendValidateCode(WebForm form, Module module) {
		String mobile = CommUtil.null2String(form.get("mobile"));
		String validateCode = "";
		// 生成4位随机验证码
		Random random = new Random();
		int rand = random.nextInt();
		validateCode = String.valueOf(Math.abs(rand)).substring(0, 4);
		// 将验证码通过短信形式发送到手机上
		try {
			int sendSmsSucOrFail = SingletonClient.getClient().sendSMS(
					new String[] { mobile },
					"尊敬的 会员\r\n您的验证码为" + validateCode
							+ "，请于60秒内使用，如果60秒内未能使用，请重新获取验证码", 3);
			String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
			System.out.print("发送注册成功短信：  " + YorN);
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		// 将验证码存放到session中
		HttpSession session = ActionContext.getContext().getSession();
		session.setAttribute("validateCode", validateCode);
		return null;
	}

	// ajax60秒session移除验证码
	public Page doMoveValidateCode(WebForm form, Module module) {
		HttpSession session = ActionContext.getContext().getSession();
		session.removeAttribute("validateCode");
		return null;
	}

	// 忘记密码手机短信回复（金客会）
	/*
	 * param : mobile 客户手机号 acount 会员账号 vali 页面输入的手机验证码 validate
	 * session中的4位随机验证码
	 */
	public Page doFindPassword(WebForm form, Module module) {
		Userinfo userinfo = new Userinfo();
		List list = new ArrayList();
		UserinfoDAO dao = new UserinfoDAO();
		String message = "";
		String acount = CommUtil.null2String(form.get("cardname"));
		String mobile = CommUtil.null2String(form.get("mobile"));
		String vali = CommUtil.null2String(form.get("validate"));
		String validate = (String) ActionContext.getContext().getSession()
				.getAttribute("validateCode");
		if (acount != null && acount.length() > 0 && mobile != null
				&& mobile.length() > 0 && validate != null
				&& validate.length() > 0) {
			list = dao.findByAcount(acount);
			if (list.size() > 0 && validate.equals(vali)) {
				userinfo = (Userinfo) list.get(0);
				if (userinfo.getMobile().equals(mobile)) {
					// sex短信中的称呼
					String sex = userinfo.getSex() ? "先生" : "女士";
					// realname短信中的名字
					String realname = userinfo.getRealname();
					String password = userinfo.getPassword();
					try {
						// 将000000初始化密码通过短信形式发送到会员手机上
						int sendSmsSucOrFail = SingletonClient
								.getClient()
								.sendSMS(
										new String[] { userinfo.getMobile() },
										"尊敬的 "
												+ realname
												+ sex
												+ "\r\n恭喜您成功找回会员中心的帐户密码：密码：000000请妥善保管！",
										3);
						String YorN = (sendSmsSucOrFail == 0) ? "成功" : "失败";
						System.out.print("发送注册成功短信：  " + YorN);
						password = CheckPassword.generatePassword("000000");
						userinfo.setPassword(password);
						dao.update(userinfo);
						message = "密码已发送到您的手机上，请查收";
					} catch (Exception e) {
						// TODO Auto-generated catch block
						e.printStackTrace();
						message = "短信发送失败！";
						form.addResult("message", message);
						return new Page("user_login", "user_login.htm", "html",
								"/web/" + thisSite.getTemplate() + "/");
					}
				} else {
					message = "请填写正确手机号(注册时填写的手机号)";
				}
			} else {
				message = "请填写正确的会员账号及验证码";
			}
		} else {
			message = "请将资料填写完整!";
		}
		form.addResult("message", message);

		return new Page("user_login", "/type.do?tid=5137397-15803053", "url");
	}

	// 重置密码并发送到邮箱
	@SuppressWarnings("unchecked")
	public Page doSendMail(WebForm form, Module module) {
		String acount = CommUtil.null2String(form.get("acount"));
		String email = CommUtil.null2String(form.get("email"));
		InternetAddress[] address = null;
		// request.setCharacterEncoding("utf8");
		try {
			ActionContext.getContext().getRequest()
					.setCharacterEncoding("utf8");
		} catch (Exception e) {
		}
		String infoMsg = "";
		Userinfo auser = null;
		UserinfoDAO userDAO = new UserinfoDAO();
		List<Userinfo> users = new ArrayList<Userinfo>();
		if (acount.length() > 0) {
			users = userDAO.findByAcount(acount);
		} else if (email.length() > 0) {
			users = userDAO.findByEmail(email);
		}
		String password = "";
		if (users.size() > 0) {
			auser = users.get(0);
			// password = auser.getPassword();
			password = "123456";
			String realpassword = CheckPassword.generatePassword(password);
			auser.setPassword(realpassword);
			userDAO.update(auser);
			String mailserver = thisSite.getMailserver();// 发出邮箱的服务器
			String From = thisSite.getMailuser();// 发出的邮箱
			String to = email;// 发到的邮箱
			String Subject = "[" + thisSite.getName() + "]忘记密码提醒";// 标题
			String type = "text/plain";// 发送邮件格式为html
			String messageText = "您在[" + thisSite.getName() + "]的密码为: "
					+ password + " 请注意保密，妥善保管！";// 发送内容
			boolean sessionDebug = false;
			try {
				// 设定所要用的Mail 服务器和所使用的传输协议
				java.util.Properties props = System.getProperties();
				props.put("mail.host", mailserver);
				props.put("mail.transport.protocol", "smtp");
				props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
				// 指明环境编码，否则在Linux环境下有可能乱码
				System.setProperty("mail.mime.charset", "UTF-8");
				// 产生新的Session 服务
				javax.mail.Session mailSession = javax.mail.Session
						.getDefaultInstance(props, null);
				mailSession.setDebug(sessionDebug);
				Message msg = new MimeMessage(mailSession);
				// 设定发邮件的人
				msg.setFrom(new InternetAddress(From));
				// 设定收信人的信箱
				address = InternetAddress.parse(to, false);
				msg.setRecipients(Message.RecipientType.TO, address);
				// 设定信中的主题
				msg.setSubject(Subject);
				// 设定送信的时间
				msg.setSentDate(new Date());
				Multipart mp = new MimeMultipart();
				MimeBodyPart mbp = new MimeBodyPart();
				// 设定邮件内容的类型为 text/plain 或 text/html
				mbp.setContent(messageText, type + ";charset=UTF-8");
				mp.addBodyPart(mbp);
				msg.setContent(mp);
				Transport transport = mailSession.getTransport("smtp");
				transport.connect(mailserver, thisSite.getMailuser(),
						thisSite.getMailpass());// 设发出邮箱的用户名、密码
				transport.sendMessage(msg, msg.getAllRecipients());
				transport.close();
				// Transport.send(msg);
				infoMsg = "邮件已顺利发送！";
				// out.println("邮件已顺利发送！");
			} catch (MessagingException mex) {
				mex.printStackTrace();
				infoMsg = "发送失败：" + mex;
			}
		} else {
			infoMsg = "帐号或邮箱错误！";
		}

		form.addResult("msg", infoMsg);
		// return module.findPage("/web/" + thisSite.getTemplate(),"login");
//		return new Page("login", "user_login.htm", "html", "/web/"
//				+ thisSite.getTemplate() + "/");
		
		return new Page("login", "user_sucPass.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 显示购物车
	@SuppressWarnings("unchecked")
	public Page doCart(WebForm form, Module module) {
		if (mySession.getAttribute("cart") != null) {
			cart = (List<Commodity>) mySession.getAttribute("cart");
		}
		form.addResult("cart", cart);
		// return module.findPage("/web/" + thisSite.getTemplate(),"cart");
		return new Page("cart", "user_cart.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 移出购物车
	@SuppressWarnings("unchecked")
	public Page doRemoveCart(WebForm form, Module module) {
		String cid = CommUtil.null2String(form.get("id"));
		News anew = newsDAO.getNewsById(cid);
		Commodity acomm = new Commodity();
		acomm.setId(anew.getId());
		acomm.setName(anew.getTitle());
		acomm.setScore(anew.getScore());
		if (mySession.getAttribute("cart") != null) {
			cart = (List<Commodity>) mySession.getAttribute("cart");
		}
		List<Commodity> newCart = new ArrayList<Commodity>();
		for (Commodity ac : cart) {
			if (!acomm.getId().equals(ac.getId())) {
				newCart.add(ac);
			} else if (ac.getNum() > 1) {
				ac.setNum(ac.getNum() - 1);
				newCart.add(ac);
			}
		}
		mySession.setAttribute("cart", newCart);
		return doCart(form, module);
	}

	// 加入购物车
	@SuppressWarnings("unchecked")
	public Page doAddCart(WebForm form, Module module) {
		String cid = CommUtil.null2String(form.get("id"));
		News anew = newsDAO.getNewsById(cid);
		Commodity acomm = new Commodity();
		acomm.setId(anew.getId());
		acomm.setName(anew.get("gift_name"));
		acomm.setTitle(anew.getTitle());
		acomm.setScore(anew.getScore());
		acomm.setNum(1);
		if (mySession.getAttribute("cart") != null) {
			cart = (List<Commodity>) mySession.getAttribute("cart");
		}
		List<Commodity> newCart = new ArrayList<Commodity>();
		boolean haveAdded = false;
		for (Commodity ac : cart) {
			if (acomm.getId().equals(ac.getId())) {
				ac.setNum(ac.getNum() + 1);
				haveAdded = true;
			}
			newCart.add(ac);
		}
		if (!haveAdded) {
			newCart.add(acomm);
		}
		mySession.setAttribute("cart", newCart);
		return doCart(form, module);
	}

	// 清空购物车
	public Page doClearCart(WebForm form, Module module) {
		try {
			mySession.removeAttribute("cart");
		} catch (Exception e) {
		}
		return doCart(form, module);
	}

	// 作品集展示
	public Page doShow(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		return new Page("show", "user_show.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 作品集管理
	public Page doEditPicType(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		String picType = CommUtil.null2String(form.get("pictype"));
		PicType thisPicType = ptDAO.getPicTypeById(picType);
		form.addResult("thisPicType", thisPicType);
		return new Page("show", "user_show_manage.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 鍙戝竷浣滃搧闆�
	public Page doAddPicType(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		PicType thisPicType = new PicType();
		String id = ptDAO.savePicType(thisPicType);
		if (id.length() > 0) {
			thisPicType.setId(id);
		}
		form.addResult("thisPicType", thisPicType);
		return new Page("show", "user_show_post.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 保存作品集
	public Page doSavePicType(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		PicType apicType = (PicType) form.toPo(PicType.class);
		// PicType apicType = new PicType();
		apicType.setName(CommUtil.null2String(form.get("name")));
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			apicType.setDate(sdf.parse(CommUtil.null2String(form.get("date"))));
		} catch (Exception e) {
			apicType.setDate(new Date());
		}
		apicType.setDisplay(1);
		String msg = "";
		try {
			ptDAO.updatePicType(apicType);
			msg = "保存成功!";
		} catch (Exception e) {
			msg = "保存失败:" + e.getMessage();
		}
		form.addResult("msg", msg);
		return doIndex(form, module);
	}

	// 保存作品集
	public Page doUpdatePicType(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		PicType apicType = ptDAO.getPicTypeById(CommUtil.null2String(form.get("id")));
		//apicType.setUserid(CommUtil.null2Int(form.get("userid")));
		apicType.setName(CommUtil.null2String(form.get("name")));
		try {
			SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
			apicType.setDate(sdf.parse(CommUtil.null2String(form.get("date"))));
		} catch (Exception e) {
			apicType.setDate(new Date());
		}
		String msg = "";
		try {
			ptDAO.updatePicType(apicType);
			msg = "保存成功!";
		} catch (Exception e) {
			msg = "保存失败:" + e.getMessage();
		}
		form.addResult("msg", msg);
		return doIndex(form, module);
	}

	// 删除作品集
	public Page doDelPicType(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		String picType = CommUtil.null2String(form.get("pictype"));
		PicType thisPicType = ptDAO.getPicTypeById(picType);
		ptDAO.delPicType(thisPicType);
		// form.addResult("thisPicType", thisPicType);
		return doIndex(form, module);
	}
	
	public Page doUpdatePicOrder(WebForm form,Module module) {
		String id = CommUtil.null2String(form.get("id"));
		int order = CommUtil.null2Int(form.get("order"));
		Pic pic = picDAO.getPicById(id);
		pic.setOrder(order);
		picDAO.updatePic(pic);
		return null;
	}

	// 删除图片
	public Page doDelPic(WebForm form, Module module) {
		if (!checkLogin()) {
			return doLogin(form, module);
		}
		boolean ret = false;
		String id = CommUtil.null2String(form.get("id"));
		if (!id.equals("")) {
			Pic apic = null;
			if (id.indexOf(",") > 0) {
				String[] ids = id.split(",");
				for (int i = 0; i < ids.length; i++) {
					if (!ids[i].isEmpty()) {
						apic = picDAO.getPicById(ids[i]);
						if (apic.getFile() != null) {
							apic.getFile().delete();
						}
						// 删除缩略图
						if (apic.getSfile() != null) {
							apic.getSfile().delete();
						}
						ret = picDAO.delPic(apic);
					}
				}
			} else {
				apic = picDAO.getPicById(id);
				if (apic.getFile() != null) {
					apic.getFile().delete();
				}
				// 删除缩略图
				if (apic.getSfile() != null) {
					apic.getSfile().delete();
				}
				// System.out.println("删除图片:"+filepath);
				ret = picDAO.delPic(apic);
			}
		}
		if (ret) {
			form.addResult("msg", "删除成功！");
		} else {
			form.addResult("msg", "删除失败！");
		}
		return doIndex(form, module);
	}

	// 供应商查询
	public Page doSupplier(WebForm form, Module module) {
		return doCart(form, module);
	}

	// 会员邮箱激活
	@SuppressWarnings("unchecked")
	public Page doSendActiveMail(WebForm form, Module module) {
		String acount = CommUtil.null2String(form.get("acount"));
		String email = CommUtil.null2String(form.get("email"));
		String semail = "";
		String mail_site = "";
		form.addResult("email", email);
		if (email.indexOf("@") > 0) {
			mail_site = email.substring(email.indexOf("@") + 1);
			form.addResult("mailsite", mail_site);
		}
		// 参数加密
		semail = StringAES.encrypt(email);
		// form.addResult("s_email", semail);
		String url = "http://" + thisSite.getDomain()
				+ "/user.do?parameter=active&email=" + semail;
		InternetAddress[] address = null;
		// request.setCharacterEncoding("utf8");
		try {
			ActionContext.getContext().getRequest()
					.setCharacterEncoding("utf8");
		} catch (Exception e) {
		}
		String infoMsg = "";
		String mailserver = thisSite.getMailserver();// 发出邮箱的服务器
		String From = thisSite.getMailuser();// 发出的邮箱
		String to = email;// 发到的邮箱
		String Subject = "[" + thisSite.getName() + "]用户激活";// 标题
		String type = "text/html";// 发送邮件格式为html
		StringBuffer messageText = new StringBuffer();
		messageText.append("Hi,您好");
		messageText.append(acount);
		messageText.append("<br>");
		messageText.append("<br>");
		messageText.append("       感谢您注册[" + thisSite.getName() + "]。<br>");
		messageText.append("<strong>请您点击链接激活账号:</strong>");
		messageText.append("<br>");
		messageText.append("<a href='");
		messageText.append(url.toString());
		messageText.append("'>").append(url.toString()).append("</a>");
		messageText.append("<br>");
		messageText.append("如果上面不是链接形式，请将地址复制到您的浏览器(例如IE)的地址栏再访问。<br>");
		messageText.append("这是一封系统邮件，请勿回复。");// 发送内容
		boolean sessionDebug = false;
		try {
			// 设定所要用的Mail 服务器和所使用的传输协议
			java.util.Properties props = System.getProperties();
			props.put("mail.host", mailserver);
			props.put("mail.transport.protocol", "smtp");
			props.put("mail.smtp.auth", "true");// 指定是否需要SMTP验证
			// 指明环境编码，否则在Linux环境下有可能乱码
			System.setProperty("mail.mime.charset", "UTF-8");
			// 产生新的Session 服务
			javax.mail.Session mailSession = javax.mail.Session
					.getDefaultInstance(props, null);
			mailSession.setDebug(sessionDebug);
			Message msg = new MimeMessage(mailSession);
			// 设定发邮件的人
			msg.setFrom(new InternetAddress(From));
			// 设定收信人的信箱
			address = InternetAddress.parse(to, false);
			msg.setRecipients(Message.RecipientType.TO, address);
			// 设定信中的主题
			msg.setSubject(Subject);
			// 设定送信的时间
			msg.setSentDate(new Date());
			Multipart mp = new MimeMultipart();
			MimeBodyPart mbp = new MimeBodyPart();
			// 设定邮件内容的类型为 text/plain 或 text/html
			mbp.setContent(messageText.toString(), type + ";charset=UTF-8");
			mp.addBodyPart(mbp);
			msg.setContent(mp);
			Transport transport = mailSession.getTransport("smtp");
			transport.connect(mailserver, thisSite.getMailuser(),
					thisSite.getMailpass());// 设发出邮箱的用户名、密码
			transport.sendMessage(msg, msg.getAllRecipients());
			transport.close();
			// Transport.send(msg);
			infoMsg = "";
		} catch (MessagingException mex) {
			mex.printStackTrace();
			infoMsg = "发送失败：" + mex;
			form.addResult("msg", infoMsg);
			return new Page("active", "user_active.htm", "html", "/web/"
					+ thisSite.getTemplate() + "/");
		}
		form.addResult("msg", infoMsg);
		form.addResult("email", email);
		// return module.findPage("/web/" + thisSite.getTemplate(),"login");
		return new Page("active", "user_active.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}

	// 会员激活
	public Page doActive(WebForm form, Module module) {
		String email = CommUtil.null2String(form.get("email"));
		// 参数解密
		email = StringAES.decrypt(email);
		System.out.println("获取到的邮件地址是:"+email);
		UserinfoDAO userinfodao = new UserinfoDAO();
		Userinfo userinfo = (Userinfo) userinfodao.findByEmail(email).get(0);
		userinfo.setActive(1);
		userinfodao.update(userinfo);
		String acount = userinfo.getAcount();
		try {
			mySession = ActionContext.getContext().getRequest()
					.getSession(true);
		} catch (Exception e) {
		}
		mySession.setAttribute("loginuser", acount);
		System.out.println("设置在线名称:" + acount);
		// msg="登陆成功！";
		onlineUser = (Userinfo) userinfodao.findActiveByAcount(acount).get(0);
		form.addResult("user", onlineUser);
		return new Page("actived", "user_actived.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
		// return doRegSuccess(form, module);
	}

	// 显示用户注册激活成功页面
	@SuppressWarnings("unchecked")
	public Page doRegSuccess(WebForm form, Module module) {

		return new Page("success", "user_success.htm", "html", "/web/"
				+ thisSite.getTemplate() + "/");
	}
	
	//上传头像
	public Page doUpAvatar(WebForm form, Module module) {
		if (form.getFileElement().keySet().size() > 0) {
			Iterator it = form.getFileElement().keySet().iterator();
			if (it.hasNext()) {
				String fieldName = (String) it.next();
				FileItem file = (FileItem) form.getFileElement().get(fieldName);
				String clientName = file.getName();
	       if (FileUtil.isImgageFile(clientName)) {//头像只能是图片
					String filePath = Globals.APP_BASE_DIR + "user/upload/avatar/";
					try {
						File fdir = new File(filePath);
						if (!fdir.exists())
							fdir.mkdirs();
						String fileName = (CommUtil.getRandString(10) + clientName.substring(clientName.lastIndexOf(".")));
						String fullFileName = "/user/upload/avatar/" + fileName;
						form.addResult("fileName", fullFileName);
						File picFile=new File(filePath + fileName);
						file.write(picFile);
						File spicFile=new File(filePath + "s_" + fileName);
						Thumbnails.of(picFile).size(150, 167).keepAspectRatio(false).toFile(spicFile);
						onlineUser.setAvatar(fullFileName);
						UserinfoDAO udao=new UserinfoDAO();
						udao.update(onlineUser);
						form.addResult("msg", "{msg:'头像上传成功！'}");
					} catch (Exception e) {
						System.out.println("文件上传错误！" + e);
						form.addResult("msg", "{error:'文件上传错误！'}");
					}
				} else {
					form.addResult("msg", "{error:'只能上传图片及附件文件！'}");
				}
			}
		}
		return module.findPage("ajax");
	}
	
	//预览头像
	public Page doPreviewAvatar(WebForm form, Module module) {
		form.addResult("msg", onlineUser.getAvatar());
		return module.findPage("ajax");
	}

	// 更改密码
	@SuppressWarnings("unchecked")
	public Page doChangePassword(WebForm form, Module module) {
		if(!checkLogin()){
			return doLogin(form, module);
		}
		String message = "";
		long userid = 0;
		int logincount = 0;
		if (onlineUser != null) {
			userid = onlineUser.getId();
			// logincount用户登录的次数
			logincount = onlineUser.getLogincount();
		}
		// 获得页面传过来的旧密码和新密码
		String oldPassword = CommUtil.null2String(form.get("oldpassword"));
		String newPassword = CommUtil.null2String(form.get("newpassword"));
		if (userid > 0) {
			UserinfoDAO userinfoDAO = new UserinfoDAO();
			Userinfo userinfo = new Userinfo();
			userinfo = userinfoDAO.findById(userid);
			if (CheckPassword.validatePassword(userinfo.getPassword(),
					oldPassword)) {
				if (!newPassword.equals("123456")) {
					if (logincount == 1) {
						userinfo.setActive(1);
					}
					newPassword = CheckPassword.generatePassword(newPassword);
					userinfo.setPassword(newPassword);
					try {
						userinfoDAO.save(userinfo);
						message = "密码修改成功";
					} catch (Exception e) {
						message = "密码修改失败";
					}
				} else {
					message = "密码不合法";
				}
			} else {
				message = "原始密码输入不对";
			}
		}
		form.addResult("message", message);
		if (message.equals("密码修改成功")) {
			HttpSession session = ActionContext.getContext().getSession();
			try {
				if (session != null) {
					System.out.println("会员退出:"
							+ session.getAttribute("loginuser"));
					session.removeAttribute("loginuser");
					// session.invalidate();
				} else {
					SessionUtil.RemoveUser(loginUser);
				}
				form.addResult("user", null);
			} catch (Exception e) {
				// 如果session已经失效,直接移出名单
				SessionUtil.RemoveUser(loginUser);
				e.printStackTrace();
			}
			return new Page("user_login", "user_login.htm", "html", "/web/"
					+ thisSite.getTemplate() + "/");
			// return new Page("index", "index.htm", "html", "/web/"
			// + thisSite.getTemplate() + "/");
		} else {
			return new Page("user_changePassword", "user_edit_password.htm",
					"html", "/web/" + thisSite.getTemplate() + "/");
		}
	}

	// 修改资料 or 注册
	// 根据onlineUser是否为空判断是注册注册还是修改资料
	@SuppressWarnings("unchecked")
	public Page doChangeInfo(WebForm form, Module module) {
		if(!checkLogin()){
			return doLogin(form, module);
		}
		// 提示信息
		String message = "";
		form.addResult("tid", tid);
		
		//用户名
		String acount = CommUtil.null2String(form.get("acount"));
		//Email
		String email = CommUtil.null2String(form.get("email"));
		//所在地址
		String homearea = CommUtil.null2String(form.get("homearea"));
		//所从事职业
		String professional = CommUtil.null2String(form.get("professional"));
		//个人标签
		String hobby = CommUtil.null2String(form.get("hobby"));
		
		UserinfoDAO userDAO = new UserinfoDAO();
		
		//用户名
		//onlineUser.setAcount(acount);
		//Email
		onlineUser.setEmail(email);
		//所在地
		onlineUser.setHomearea(homearea);
		//职业
		onlineUser.setProfessional(professional);
		//个人标签
		onlineUser.setHobby(hobby);
		
		try {
			userDAO.save(onlineUser);
				message = "资料修改成功";
		}catch (Exception e) {
				message = "资料修改失败";
		}

		form.addResult("acount", acount);
		form.addResult("email", email);
		form.addResult("homearea", homearea);
		form.addResult("professional", professional);
		form.addResult("hobby", hobby);
		
		return new Page("user_profile", "user_profile.htm", "html",
					"/web/" + thisSite.getTemplate() + "/");

	
	}
	//jlm
	public Page doComment(WebForm form, Module module) {
		com.knife.news.model.Comment mycomm = (com.knife.news.model.Comment)form.toPo(com.knife.news.model.Comment.class);
		boolean result = false;
		
		String userid= CommUtil.null2String(onlineUser.getId());
		int uid = CommUtil.null2Int(onlineUser.getId());
		//newsId
		String newsid = CommUtil.null2String(form.get("newsid"));
		News anew = newsDAO.getNewsById(newsid);
		String commenttext = CommUtil.null2String(form.get("comment"));
		String id = CommUtil.null2String(form.get("id"));
		
		mycomm.setDate(new Date());
		mycomm.setUser(userid);
		mycomm.setUid((long)uid);
		mycomm.setComment(commenttext);
		mycomm.setNews_id(anew.getId());
		
		if(thisSite.getCommcheck()==0){
			mycomm.setDisplay(1);
		}else{
		mycomm.setDisplay(0);
		}
		/*
		Comment rcomm = commentDAO.getCommentById(id);
		Comment acomm = new Comment(mycomm);
		if(rcomm!=null){
			result = commentDAO.updateComment(acomm);
		}else{
			
			result = commentDAO.saveComment(acomm);
		}
		*/
		Comment acomm = new Comment(mycomm);
		result = commentDAO.addComment(acomm);
		
		if(result){
			form.addResult("msg", "提交成功！");
			return module.findPage("ajax");
		}else{
			form.addResult("msg", "提交失败！");
			return module.findPage("ajax");
		}
			
	}
	//jlm
	public Page doDeleteComment(WebForm form, Module module) {
		String id = CommUtil.null2String(form.get("id"));
		boolean result = false;
		if(id.indexOf(",")>0){
			String[] ids = id.split(",");
			for (int i = 0; i < ids.length; i++) {
				Comment comm = commentDAO.getCommentById(ids[i]);
				result = commentDAO.delComment(comm);
			}
		}else{
			//News news = newsdao.getNewsById(id);
			Comment comm = commentDAO.getCommentById(id);
			result = commentDAO.delComment(comm);
		}
		//News news = newsdao.getNewsById(id);
		if (result){
			form.addResult("msg", "删除成功！");
			return module.findPage("ajax");
		} else {
			form.addResult("msg", "删除失败！");
			return module.findPage("ajax");
		}
		
	}

	private boolean checkLogin() {
		if (null != mySession.getAttribute("loginuser")) {
			return true;
		} else {
			return false;
		}
	}

}
